import TencentCloudChat from "@tencentcloud/chat";
// import TIMUploadPlugin from "tim-upload-plugin";
import LibGenerateTestUserSig from "./lib-generate-test-usersig-es.min";

/**
 * Signature expiration time, which should not be too short
 * Time unit: second
 * Default time: 7 * 24 * 60 * 60 = 604800 = 7days
 */
const EXPIRE_TIME = 604800;

class TIM {
  isReady = false;
  $timInstance = null;
  SDKAppID = null;
  SDKSecretKey = null;
  userInfo = null;
  expireTime = EXPIRE_TIME;
  _onWarning(message) {
    console.info(message);
  }
  constructor({
    SDKAppID,
    SDKSecretKey,
    expireTime,
    logLevel,
    onReadyChange,
    onError,
    onWarning,
  }) {
    if (!SDKAppID) {
      throw new Error("SDKAppID is required");
    }
    if (!SDKSecretKey) {
      throw new Error("SDKSecretKey is required");
    }
    this.SDKAppID = SDKAppID;
    this.SDKSecretKey = SDKSecretKey;

    if (expireTime) {
      this.expireTime = expireTime;
    }

    if (onWarning) {
      this._onWarning = onWarning;
    }

    this._init({
      SDKAppID,
      logLevel,
      onReadyChange,
      onError,
    });
  }
  _init({ SDKAppID, logLevel, onReadyChange, onError }) {
    this.$timInstance = TencentCloudChat.create({ SDKAppID });
    this.$timInstance.setLogLevel(logLevel || 1);
    // this.$timInstance.registerPlugin({ "tim-upload-plugin": TIMUploadPlugin });

    // 监听登录
    this.$timInstance.on(TencentCloudChat.EVENT.SDK_READY, function onReady() {
      // this.isReady = true
      onReadyChange && onReadyChange(true);
    });

    // 监听注销登录
    this.$timInstance.on(
      TencentCloudChat.EVENT.SDK_NOT_READY,
      function onReady() {
        // this.isReady = false
        // this.userInfo = null
        // onReadyChange && onReadyChange(false)
      }
    );

    // 监听错误
    this.$timInstance.on(TencentCloudChat.EVENT.ERROR, (res) => {
      onError && onError(res);
    });

    // 监听消息接收
    this.$timInstance.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, (res) => {
      console.log("res--->", res);
    });
  }
  // 登录
  login(userID) {
    if (this.isReady) return;
    if (!userID) {
      throw new Error("userID is required");
    }
    const _userID = userID.toString();
    const generator = new LibGenerateTestUserSig(
      this.SDKAppID,
      this.SDKSecretKey,
      this.expireTime
    );
    const userSig = generator.genTestUserSig(_userID);
    this.userInfo = { userID: _userID, userSig };
    return this.$timInstance.login(this.userInfo);
  }
  // 注销登录
  logout = () => {
    return this.$timInstance.logout();
  };
  getConversationList() {
    return this.$timInstance
      .getConversationList()
      .then((res) => {
        if (res.code === 0) {
          return res.data.conversationList || [];
        }
        return [];
      })
      .catch((err) => {
        return [];
      });
  }
  sendTextMessage({ toUserID, conversationType, text }) {
    return this.sendMessage({
      toUserID,
      conversationType,
      data: {
        type: "text",
        value: { text },
      },
    });
  }
  sendFileMessage({ toUserID, conversationType, file }) {
    return this.sendMessage({
      toUserID,
      conversationType,
      data: {
        type: "file",
        value: {
          name: file.name,
          size: file.size,
          url: file.url,
        },
      },
    });
  }
  sendImageMessage({ toUserID, conversationType, file }) {
    return this.sendMessage({
      toUserID,
      conversationType,
      data: {
        type: "image",
        value: {
          name: file.name,
          size: file.size,
          url: file.url,
        },
      },
    });
  }
  sendMessage({
    toUserID,
    data,
    conversationType = TencentCloudChat.TYPES.CONV_C2C,
  }) {
    if (this.isReady) {
      return Promise.reject(new Error("系统还没准备好, 请稍后发送信息..."));
    }
    if (!toUserID) {
      return Promise.reject(new Error("请选择沟通的对象再发送消息"));
    }

    if (data.type === "text" && !data.value.text?.trim()) {
      return Promise.reject(new Error("请输入聊天内容"));
    }

    const message = this.$timInstance.createCustomMessage({
      to: toUserID.toString(),
      conversationType,
      payload: {
        data: JSON.stringify(data),
      },
      // 如果您发消息需要已读回执，需购买旗舰版或企业版套餐，并且创建消息时将 needReadReceipt 设置为 true
      needReadReceipt: true,
    });

    return this.$timInstance.sendMessage(message);
  }
}

export default TIM;
